const express = require('express');
const crypto = require('crypto');
const axios = require('axios');
const jwt = require('jsonwebtoken');
const mongoose = require('../db/db.js');
const debug = require('debug')('a-sokio-yun:server');
const router = express.Router();
const userMod = require('../db/cloudControl/userMod.js');
const deviceShe = require('../db/cloudControl/deviceSchema');


// const fs = require('fs');
const { publicPath, ppxxxkkk, appName, TOKEN_SECRET_KEY, maxDeviceNum } = require('../serverOpt');

router.get('/login', function (req, res) {
    if (req.session && req.session.userName) {
        res.sendFile(publicPath + '/jinzhu.html');
    } else {
        res.sendFile(publicPath + '/page/login/login.html');
    }
});

router.post('/login', async function (req, res) {
    try {
        const { user_name, password } = req.body;
        const userDoc = await userMod.findOne({ userName: user_name });
        if (userDoc) {
            if (userDoc.userPass.encryptedData == encryptByIv(userDoc.userPass, password)) {
                req.session.userName = user_name;
                req.session.userId = userDoc._id;
                req.session.userLevel = userDoc.userLevel;
                const token = jwt.sign({
                    userName:userDoc.userName
                }, TOKEN_SECRET_KEY, { expiresIn: '2h' });
                const parsedList = JSON.parse(userDoc.permissionList);
                parsedList.forEach(item=>{
                    if(item.name == '系统管理'){
                        for (const i of item.children) {
                            if(i.name == '字典管理') i.disabled = true;
                        }
                    }
                })
                return res.json({
                    code: 0,
                    msg: '登录成功',
                    data: {
                        userName: user_name,
                        userId: userDoc._id,
                        userLevel: userDoc.userLevel,
                        maxDeviceNum:userDoc.maxDeviceNum,
                        token:'Bearer ' + token,
                        permission_list:JSON.stringify(parsedList)
                    },
                });
            } else {
                throw new Error('账号或密码验证失败.');
            }
        } else {
            throw new Error('账号或密码验证失败');
        }
    } catch (error) {
        debug('登录错误:', error.message);
        res.json({
            code: -1,
            msg: '登录失败:' + error.message,
            data: null,
        });
    }
});

router.post('/logout', function (req, res) {
    debug('退出登录之前req.session', req.session);
    req.session.destroy();
    debug('退出登录之后req.session', req.session);
    res.json({ code: 0, msg: '登出成功' });
});

async function asyncHttpRedir(url) {
    try {
        await axios.get(url, {
            headers: {
                Accept: '*/*',
                Connection: 'keep-alive',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
            },
            maxRedirects: 0, // 禁止自动重定向
        });
    } catch (error) {
        if (error.response && error.response.status === 302) {
            // Handle redirect here
            return error.response.headers.location;
        }
    }
}

function encryptByIv(pwdDoc, newPwdStr) {
    const iv = Buffer.from(pwdDoc.iv, 'hex');
    // console.log(iv);
    const cipher = crypto.createCipheriv('aes-256-cbc', ppxxxkkk, iv);
    let encrypted = cipher.update(newPwdStr, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
}

module.exports = router;
